package com.stu;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author MI
 * @ClassName HttpPostXml.java
 * @createTime 2021年11月16日 09:39:00
 */
@Slf4j
public class HttpPostXml {
    @Test
    public void send() {
        // String xmlStr = "<User><id>133</id><sex>男</sex><age>18</age></User>";
        // String resopnse = httpPostXml("http://localhost:9101/hello/xml/", xmlStr);
        String xmlStr = "<User><id>133</id><sex>男</sex><age>18</age></User>";
        String resopnse = httpPostXml("http://localhost:8080/bayonet/bus/api/dates", xmlStr);
        System.out.println(resopnse);
    }

    public static String httpPostXml(String url, String xmlStr) {
        HttpClient httpClient = new DefaultHttpClient();
        org.apache.http.client.methods.HttpPost method = new HttpPost(url);
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(xmlStr, StandardCharsets.UTF_8);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/xml");
        method.setEntity(entity);
        try {
            HttpResponse result = httpClient.execute(method);
            if (result.getStatusLine().getStatusCode() == 200) {
                String strResult = EntityUtils.toString(result.getEntity());
                System.out.println("请求响应:" + strResult);
                return EntityUtils.toString(result.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (IOException e) {
            log.error("post xml提交失败", e);
        }
        return null;

    }
}
